package com.sx.gongzhong.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.ExposureTypeAdapter;
import com.sx.gongzhong.adapter.MultiImageAdapter;
import com.sx.gongzhong.model.LocationBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.model.PublicBean;
import com.sx.gongzhong.model.PublicTotalBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.pest.ExposureAddPest;
import com.sx.gongzhong.pest.PublicPest;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IPublicView;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.CountEditText;
import com.sx.gongzhong.widget.LoadDialog;
import com.sx.gongzhong.widget.MyPopupWindow;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

import static com.sx.gongzhong.R.id.tv_right;

/**
 * 爆料新增
 */
public class ExposureAddActivity extends BaseActivity implements View.OnClickListener
            ,UploadFileView,IVoidView,IPublicView{

    @BindView(R.id.et_Title)
    EditText et_Title;
    @BindView(R.id.et_Content)
    CountEditText et_Content;
    @BindView(R.id.tv_Type)
    TextView tv_Type;
    @BindView(R.id.tv_Location)
    TextView tv_Location;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    @BindView(R.id.tv_count)
    TextView tvCount;
    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    /**上传后的地址所选文件*/
    private List<String> fileList;
    private MyPopupWindow popType;
    private String typeId="";
    //位置信息
    private LocationBean locationBean;
    private IDataStorage dataStorage;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_exposure_add);
        setTitleName(R.string.exposure_add);
        setTitleRight(R.string.confirm);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        tv_Type.setOnClickListener(this);
        tv_Location.setOnClickListener(this);
        findViewById(tv_right).setOnClickListener(this);
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setSelectMax(10);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        et_Content.setMaxNum(500);
        et_Content.setOnEditTextCountLisener(new CountEditText.OnEditTextCountLisener() {
            @Override
            public void setCount(int currentCount) {
                tvCount.setText(currentCount+"/500");
            }
        });
        //获取爆料类型
        dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        PublicTotalBean bean=dataStorage.load(PublicTotalBean.class,"brokeNewsType");
        if (bean!=null&&bean.getChildren()!=null){
            createPopType(bean.getChildren());
        }else {
            // 获取爆料类型
            new PublicPest(this).getPublicList("brokeNewsType");
        }
    }



    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 10 - selectList.size();
            if (max > 0) {
                PictureSelector.create(ExposureAddActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .maxSelectNum(max)// 最大图片选择数量 int
                        //.previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .withAspectRatio(16, 9)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(100)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            } else {
                ToastUtils.showToast(ExposureAddActivity.this, "最多上传10张");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case 100://位置选择
                    locationBean= (LocationBean) data.getSerializableExtra("Location");
                    if (locationBean!=null){
                        tv_Location.setText(locationBean.getAddress());
                    }else {
                        tv_Location.setText("不显示当前位置");
                    }
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_Type:
                if (popType != null){
                    popType.showAsDropDown(findViewById(R.id.toolbar));
                }else {
                    ToastUtils.showToast(this,"类型加载失败 请检查网络");
                }
                break;
            case R.id.imv_Cancel:
                popType.dismiss();
                break;
            case R.id.tv_Location:
                startActivityForResult(new Intent(this,LocationActivity.class),100);
                break;
            case R.id.tv_right:
               submit();
                break;
        }
    }

    /**
     * 提交数据
     */
    private void submit() {
        String title=et_Title.getText().toString().trim();
        if (BaseUtil.isEmpty(title)){
            et_Title.setError("标题不能为空");
            return;
        }
        String content=et_Content.getText().toString().trim();
        if (BaseUtil.isEmpty(content)){
            et_Content.setError("你想说什么呢?");
            return;
        }
        if (BaseUtil.isEmpty(typeId)){
            ToastUtils.showToast(this,"请选择类型");
            return;
        }
        if (selectList.size()>0){
            List<File> files = new ArrayList<>();
            for (PhotoBean localMedia : selectList) {
                files.add(new File(localMedia.getPath()));
            }
            LoadDialog.show(this, "正在上传图片...");
            new UploadFilePest(this).uploadFile(this, files);
        }else {
            submitDone();
        }
    }

    /**
     * 提交结果
     */
    private void submitDone() {
        LoadDialog.show(this, "提交中");
        new ExposureAddPest(this).addExposure(typeId,locationBean,et_Title.getText().toString().trim()
        ,et_Content.getText().toString().trim(),fileList);
    }

    /**
     * 爆料类型
     */
    private void createPopType(final List<PublicBean> beanList) {
        if (popType==null){
            View view = LayoutInflater.from(this).inflate(R.layout.pop_exposure_type, null);
            popType = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            popType.setTouchable(true);
            popType.setOutsideTouchable(false);
            popType.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
            ListView listView= (ListView) view.findViewById(R.id.listView);
            view.findViewById(R.id.imv_Cancel).setOnClickListener(this);
            if (beanList!=null&&beanList.size()>0){
                ExposureTypeAdapter adapter=new ExposureTypeAdapter(this,R.layout.item_exposure_type,beanList);
                listView.setAdapter(adapter);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        tv_Type.setText(beanList.get(position).getName());
                        typeId=beanList.get(position).getId();
                        popType.dismiss();
                    }
                });
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }


    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        if(fileList==null){
            fileList=new ArrayList<>();
        }
        for (PhotoBean bean:beans){
            fileList.add(bean.getId());
        }
        submitDone();
    }

    @Override
    public void voidView(String str) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,str);
        MyRxBus.get().post(new MsgEvent("ExposureFragment",1,null));
        MyRxBus.get().post(new MsgEvent("MainPagerFragment",1,null));
        finish();
    }

    @Override
    public void getPublicList(List<PublicBean> beanList) {
        if (beanList!=null){
            createPopType(beanList);
        }
    }
}
